<template>
  <div class="app-container">
    <div class="box ph-30">
      <div class="panel">
        <div class="panel-header">
          <h3 class="panel-title">填写报名信息</h3>
        </div>
        <div class="panel-body">
          <el-form
            ref="ruleFormRef"
            label-width="120px"
            class="signForm"
            :model="form"
            :rules="rules"
          >
            <el-row>
              <el-col :span="8" :offset="2">
                <el-form-item label="照片" prop="picUrl">
                  <ImageUpload
                    v-model="form.picUrl"
                    class="threeFour"
                    :limit="1"
                    :is-show-tip="false"
                  />
                  <span class="tip"><i>*</i>请上传近期 彩色免冠照片</span>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="姓名" prop="realName">
                  <el-input v-model="form.realName" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="form.sex">
                    <el-radio label="0" size="large">男</el-radio>
                    <el-radio label="1" size="large">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="证件类型" prop="idcType">
                  <el-select
                    v-model="form.idcType"
                    placeholder="请选择证件类型"
                  >
                    <el-option
                      v-for="item in certificates"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="证件号码" prop="idcCode">
                  <el-input
                    v-model="form.idcCode"
                    placeholder="请输入证件号码"
                  />
                </el-form-item>
                <el-form-item label="出生日期" prop="birth">
                  <el-date-picker
                    v-model="form.birth"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择出生日期"
                  />
                </el-form-item>

                <el-form-item label="联系方式" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入联系方式" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <el-row>
            <el-col :span="16" :offset="4">
              <h3>报名项目</h3>
              <el-table :data="trainList" border>
                <el-table-column label="科目类型" prop="typeStr" />
                <el-table-column
                  label="科目名称"
                  prop="projectName"
                  min-width="200"
                />

                <el-table-column prop="date" label="必报科目">
                  <template #default="props">
                    <div v-if="props.row.isNecessary == 1">是</div>
                    <div v-else>否</div>
                  </template>
                </el-table-column>
                <el-table-column label="科目费用（元）" prop="cost" />
                <el-table-column label="操作">
                  <template #default="scope">
                    <el-checkbox
                      :disabled="scope.row.isNecessary == 1"
                      v-model="scope.row.check"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </div>
        <div class="panel-footer text-center">
          <el-button type="success" round @click="submitForm()"
            >下一步</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import { getCurrentInstance, onMounted } from "@vue/runtime-core";
import * as train from "@/api/train/pc";
import { toRefs } from "@vueuse/shared";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const trainList = ref([]);
const data = reactive({
  form: {},
  userInfo: {},
  trainData: {},
  rules: {
    picUrl: { required: true, message: "请上传您的照片", trigger: "blur" },
    realName: { required: true, message: "请填写您的姓名", trigger: "blur" },
    sex: { required: true, message: "请选择您的性别", trigger: "change" },
    birth: { required: true, message: "请填写您的生日", trigger: "blur" },
    idcType: { required: true, message: "请选择您的证件", trigger: "change" },
    idcCode: { required: true, message: "请填写您的证件号", trigger: "blur" },
    phone: { required: true, message: "请填写您的联系方式", trigger: "blur" },
  },
  certificates: [
    {
      value: "0",
      label: "居民身份证",
    },
    {
      value: "1",
      label: "护照",
    },
    {
      value: "2",
      label: "其他",
    },
  ],
  participantsInfoArr: [],
  countryList: [],
  hasCptPersonInfo: false,
  personId: "0",
});
const { trainData, form, rules, certificates, participantsInfoArr } =
  toRefs(data);
onMounted(() => {
  initData();
  getUserInfo();
});

async function initData() {
  let res = await train.getTrainDetails({ id: route.query.id });
  trainData.value = res.data;
  res.data.trainProjectsList?.forEach((item) => {
    item.typeStr = "培训";
    if (item.isNecessary == 1) {
      item.check = true;
    } else {
      item.check = false;
    }
    trainList.value.push(item);
  });
  res.data.examProjectsList?.forEach((item) => {
    item.typeStr = "考试";
    if (item.isNecessary == 1) {
      item.check = true;
    } else {
      item.check = false;
    }
    trainList.value.push(item);
  });
}

async function getUserInfo() {
  let res = await train.getUserInfo();
  form.value = res.data;
}

function submitForm() {
  proxy.$refs["ruleFormRef"].validate(async (valid, fields) => {
    if (valid) {
      var pattern = /^1[345789]\d{9}$/;
      if (!pattern.test(form.value.phone)) {
        ElMessage.error("请输入正确的手机号");
        return;
      }
      if (
        form.value.idcType == 0 &&
        !/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(form.value.idcCode)
      ) {
        ElMessage.error("请输入正确的身份证号码");
        return;
      }
      // 验证补充信息必填
      for (const n in participantsInfoArr.value) {
        if (
          participantsInfoArr.value[n].status == 0 &&
          !participantsInfoArr.value[n].value
        ) {
          ElMessage.error("请完善必填字段");
          return;
        }
      }

      // 赛选培训科目
      let arr1 = [];
      let arr2 = [];
      let arr = JSON.parse(JSON.stringify(trainList.value));
      arr.forEach((item) => {
        if (item.typeStr == "培训") {
          if (item.check) arr1.push(item.id);
        } else {
          if (item.check) arr2.push(item.id);
        }
      });

      let res = await train.signUp({
        examIdsArray: arr2,
        projectIdsArray: arr1,
        venueId: trainData.value.venueId,
        trainId: trainData.value.id,
        id: trainData.value.signId,
      });

      if (trainData.value.hotelList.length <= 0) {
        // 没有酒店信息
        router.push({
          name: "trainBill",
          query: {
            id: trainData.value.id,
            venueId: trainData.value.venueId,
          },
        });
      } else {
        // 有酒店信息
        if (res.code == 200)
          router.push({
            path: "Step2",
            query: {
              id: trainData.value.id,
            },
          });
      }
    } else {
      console.log(form.value, fields);
    }
  });
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 0;
  background: #f5f7f9;
}

.panel-footer .el-button--success {
  background: linear-gradient(270deg, #39dba7, #38ef7d);
  border: none;
  padding: 0 40px;
  font-size: 16px;
}

.signForm {
  .el-form-item__label {
    color: #4c5359;
  }
}

.tip {
  font-size: 13px;
  color: #999;
  margin: 10px 0;

  i {
    color: red;
    margin: 0 4px 0 0;
  }
}

.threeFour {
  width: 100%;
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 160px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 160px;
}

.red {
  color: #f56c6c;
}
</style>
